let overlay = null;
let isActive = false;
let currentColor = '#c9e0c1';
let currentOpacity = 30;

// 初始化时获取存储的颜色设置并自动开启护眼模式
chrome.storage.local.get(['color', 'opacity'], function(result) {
  if (result.color) {
    currentColor = result.color;
  }
  if (result.opacity) {
    currentOpacity = result.opacity;
  }
  
  // 自动开启护眼模式
  createOverlay();
});

function createOverlay() {
  if (!isActive) {
    overlay = document.createElement('div');
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      z-index: 9999;
    `;
    updateOverlay();
    document.body.appendChild(overlay);
    isActive = true;
  }
}

function updateOverlay() {
  if (overlay) {
    const rgb = hexToRgb(currentColor);
    overlay.style.backgroundColor = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${currentOpacity / 100})`;
  }
}

function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'toggle') {
    if (!isActive) {
      createOverlay();
    } else {
      overlay.remove();
      isActive = false;
    }
    // 发送状态更新消息
    chrome.runtime.sendMessage({ action: 'updateState', isActive });
  } else if (request.action === 'getState') {
    sendResponse({ isActive });
  } else if (request.action === 'updateColor') {
    currentColor = request.color;
    currentOpacity = request.opacity;
    updateOverlay();
  }
  return true;
}); 